package com.yupixm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupixm.common.BaseResponse;
import com.yupixm.common.ErrorCode;
import com.yupixm.common.ResultUtils;
import com.yupixm.exception.BusinessException;
import com.yupixm.pojo.domain.User;
import com.yupixm.pojo.domain.request.UserLoginRequest;
import com.yupixm.pojo.domain.request.UserRegisterRequest;
import com.yupixm.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.yupixm.contants.UserConstant.ADMIN_ROLE;
import static com.yupixm.contants.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/users")
//@EnableWebMvc
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求体
     * @return 注册的ID
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        //判断是否为空，
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"输入参数有为空");
        }
        //企业的标准写法
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        //其中任意为空就不进行下去
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"输入有空值");
        }
        long userId = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求体
     * @param request          请求体
     * @return 登录的用户
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"输入参数有为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"输入有空值");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"登录态为空");
        }
        int i = userService.userLogout(request);
        return ResultUtils.success(i);
    }

    /**
     * 获取当前用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        //根据request获取当前用户信息
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User userCurrent = (User) userObj;
        if (userCurrent == null) {
           throw new BusinessException(ErrorCode.NULL_ERROR,"用户为空");
        }
        //获取用户id，再查询数据库返回最新的用户状态
        Long id = userCurrent.getId();
        User user = userService.getById(id);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
//        return safetyUser;
    }

    /**
     * 用户查询（要管理员权限）
     *
     * @param userName 可根据用户名查询，也可查询全部
     * @param request  请求体
     * @return 查询结果集
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String userName, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH,"无权限");
        }
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            qw.like("userName", userName);
        }
        List<User> userList = userService.list(qw);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 逻辑删除
     *
     * @param id      用户id
     * @param request 请求体
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable long id, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH,"无权限");
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"id不能小于0");
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 判断是否为管理员
     *
     * @param request 请求体
     * @return 返回 T / F
     */
    public boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

}
